package com.example.recordingpen_datacollection.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.recordingpen_datacollection.entity.Device;
import com.example.recordingpen_datacollection.entity.Login;
import com.example.recordingpen_datacollection.mapper.DeviceMapper;
import com.example.recordingpen_datacollection.result.exceptionhandler.JWException;
import com.example.recordingpen_datacollection.service.DeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.recordingpen_datacollection.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xg
 * @since 2023-11-14
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements DeviceService {

    @Autowired
    private LoginService loginService;


    @Override
    public boolean devMessageRecord(Device device) {

        {
            QueryWrapper wrapperPhone = new QueryWrapper();
            wrapperPhone.eq("phone",device.getPhone());
            Login one = loginService.getOne(wrapperPhone);
            if(one == null){
                throw new JWException(500,"手机号账号不存在");
            } else {
                device.setLoginId(one.getId());
            }
        }



        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("login_id",device.getLoginId());
        wrapper.eq("phone",device.getPhone());
        wrapper.eq("dev_name",device.getDevName());
        wrapper.eq("message",device.getMessage());
        wrapper.eq("dev_type",device.getDevType());

        Device one = this.getOne(wrapper);
        if(one == null){
            boolean save = this.save(device);
            if(!save){
                throw new JWException(500,"首次添加失败");
            }
        } else {
            System.out.println(one.toString());
            Device device1 = new Device();
            device1.setDevId(one.getDevId());
            device1.setCount(one.getCount()+1);
            boolean b = this.updateById(device1);
            if(!b){
                throw new JWException(500,"添加Count失败");
            }
        }
        return true;
    }
}
